package com.sfac.javaEE.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sfac.javaEE.common.Result;
import com.sfac.javaEE.entity.User;
import com.sfac.javaEE.service.UserService;
import com.sfac.javaEE.service.Impl.UserServiceImpl;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet(value = {"/api/user/*"})
public class UserServlet extends HttpServlet {

    private ObjectMapper om = new ObjectMapper();
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // path 参数
        String path = req.getRequestURI();
        String[] temp = path.split("/");
        String last = temp[temp.length - 1];
        int id = 0;
        if (StringUtils.isNotBlank(last) && last.matches("^[0-9]*$")) {
            id = Integer.parseInt(last);
        } else {
            throw new ServletException("Id is invalid.");
        }

        // 调用 service 获取 user 对象
        User user = userService.getUserById(id);

        // 把 user 返回
        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write(om.writeValueAsString(user));
        pw.flush();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 获取 json 数据，序列化为 user 对象
        StringBuffer sb = new StringBuffer();
        String line = null;
        BufferedReader br = req.getReader();
        while ((line =  br.readLine()) != null) {
            sb.append(line);
        }
        User user = StringUtils.isNotBlank(sb) ?
                om.readValue(sb.toString(), User.class) :
                new User();

        // 调用 service，处理插入业务逻辑
        Result<User> result = userService.insertUser(user);

        // 以 json 格式返回数据
        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write(om.writeValueAsString(result));
        pw.flush();
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端传递的 user 对象
        // 查询参数 || form 表单参数
        User user = new User();
        user.setUserName(req.getParameter("userName"));
        user.setPassword(req.getParameter("password"));
        user.setId(Integer.parseInt(req.getParameter("id")));

        // 调用 service 处理业务
        Result<User> result = userService.updatetUser(user);

        // 返回 result
        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write(om.writeValueAsString(result));
        pw.flush();
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // path 参数
        String path = req.getRequestURI();
        String[] temp = path.split("/");
        String last = temp[temp.length - 1];
        int id = 0;
        if (StringUtils.isNotBlank(last) && last.matches("^[0-9]*$")) {
            id = Integer.parseInt(last);
        } else {
            throw new ServletException("Id is invalid.");
        }

        // 调用 service 处理业务逻辑
        Result<Object> result = userService.deleteUserById(id);

        // 返回 result
        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        pw.write(om.writeValueAsString(result));
        pw.flush();
    }
}
